package com.example.smartvillage;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import androidx.core.os.HandlerCompat;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.example.smartvillage.cunmin.AutoAdaptModel;
import com.example.smartvillage.model.BannerBean;
import com.example.smartvillage.model.NewsData;
import com.example.smartvillage.model.Notice;
import com.example.smartvillage.model.User;
import com.example.smartvillage.model.WeatherData;
import com.example.smartvillage.onenet.MyOneNetApi;
import com.example.smartvillage.utils.News;
import com.example.smartvillage.utils.Weather;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;

public class MainViewModel extends ViewModel {

    private static final String TAG = "MainViewModel";

    ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    Handler mainThreadHandler = HandlerCompat.createAsync(Looper.getMainLooper());

    private MutableLiveData<User> user;
    private MutableLiveData<MyOneNetApi> myOneNetApi;
    //主页
    private MutableLiveData<List<BannerBean>> bannerBeans;
    private MutableLiveData<WeatherData> weatherData;
    private MutableLiveData<List<Notice>> NoticeList;
    private MutableLiveData<List<NewsData.ResultDTO.DataDTO>> newsData;
    //村民
    private MutableLiveData<boolean[]> bulbStates;
    private MutableLiveData<boolean[]> windowStates;
    private MutableLiveData<boolean[]> balconyStates;
    private MutableLiveData<boolean[]> doorStates;
    private MutableLiveData<Boolean> leaveHomeState;
    private MutableLiveData<AutoAdaptModel> autoAdaptModel;
    //村委
    private MutableLiveData<Boolean> roadblockState;
    private MutableLiveData<boolean[]> streetLampStates;

    public LiveData<User> getUser() {
        if (user == null) {
            user = new MutableLiveData<>();
            loadUser();
        }
        return user;
    }

    public void setUser(User newUser) {
        user.setValue(newUser);
    }

    private void loadUser() {
        setUser(new User());
    }

    public LiveData<MyOneNetApi> getMyOneNetApi() {
        if (myOneNetApi == null) {
            myOneNetApi = new MutableLiveData<>();
            loadMyOneNetApi();
        }
        return myOneNetApi;
    }

    public void setMyOneNetApi(MyOneNetApi newMyOneNetApi) {
        myOneNetApi.setValue(newMyOneNetApi);
    }

    private void loadMyOneNetApi() {
        myOneNetApi.setValue(new MyOneNetApi(executorService, mainThreadHandler));

    }

    //头图
    public LiveData<List<BannerBean>> getListBannerBean() {
        if (bannerBeans == null) {
            bannerBeans = new MutableLiveData<>();
            loadListBannerBean();
        }
        return bannerBeans;
    }

    public void setListBannerBean(List<BannerBean> newBannerBeans) {
        bannerBeans.setValue(newBannerBeans);
    }

    private void loadListBannerBean() {
        List<BannerBean> beans = new ArrayList<>();
        BannerBean bannerBean1 = new BannerBean();
        BannerBean bannerBean2 = new BannerBean();
        BannerBean bannerBean3 = new BannerBean();
        bannerBean1.setImgRes(R.drawable.banner1);
        beans.add(bannerBean1);
        bannerBean2.setImgRes(R.drawable.banner2);
        beans.add(bannerBean2);
        bannerBean3.setImgRes(R.drawable.banner3);
        beans.add(bannerBean3);
        setListBannerBean(beans);
    }

    //天气
    public LiveData<WeatherData> getWeatherData() {
        if (weatherData == null) {
            weatherData = new MutableLiveData<>();
            loadWeatherData();
        }
        return weatherData;
    }

    public void setWeatherData(WeatherData newWeatherData) {
        weatherData.setValue(newWeatherData);
    }

    private void loadWeatherData() {
        executorService.submit(() -> {

            Log.d(TAG, "查询天气的线程："+Thread.currentThread().getName());
            WeatherData weatherData = Weather.queryWeather("韶关", "537867f932fdd88a9daff2158b3fed84");

            mainThreadHandler.post(() -> {
                //保存天气数据到ViewModel
                if (weatherData != null) {
                    setWeatherData(weatherData);
                }
            });

        });
    }

    //公告
    public LiveData<List<Notice>> getNoticeList() {
        if (NoticeList == null) {
            NoticeList = new MutableLiveData<>();
            loadNoticeList();
        }
        return NoticeList;
    }

    public void setNoticeList(List<Notice> newNoticeList) {
        NoticeList.setValue(newNoticeList);
    }

    private void loadNoticeList() {
        //更新公告
        BmobQuery<Notice> bmobQuery = new BmobQuery<>();
        bmobQuery.order("-createdAt");
        bmobQuery.findObjects(new FindListener<Notice>() {
            public void done(List<Notice> list, BmobException e) {
                if(e==null){
                    setNoticeList(list);
                    Log.d("Bmob","公告更新成功"+list);
                }else{
                    Log.e("Bmob","公告更新失败，错误码：" + e.getErrorCode());
                }
            }
        });
    }

    //新闻
    public LiveData<List<NewsData.ResultDTO.DataDTO>> getNewsData() {
        if (newsData == null) {
            newsData = new MutableLiveData<>();
            loadNewsData();
        }
        return newsData;
    }

    public void setNewsData(List<NewsData.ResultDTO.DataDTO> newNewsData) {
        newsData.setValue(newNewsData);
    }

    public void loadNewsData() {
        //获得News实例
        News news = new News(executorService, mainThreadHandler);
        //传递参数
        news.GetNewsList("top", 1, 10, response -> {

            JsonObject json = response.body();
            if (json != null && json.get("error_code").getAsInt() == 0) {

                JsonArray jsonArray = json.get("result").getAsJsonObject().get("data").getAsJsonArray();
                List<NewsData.ResultDTO.DataDTO> dataDTOList = new ArrayList<>();

                for (int i = 0; i < jsonArray.size(); i++) {
                    dataDTOList.add(new Gson()
                            .fromJson(jsonArray.get(i).toString(), NewsData.ResultDTO.DataDTO.class));
                }
                setNewsData(dataDTOList);
            }
        });
    }

    //灯泡
    public LiveData<boolean[]> getBulbStates() {
        if (bulbStates == null) {
            bulbStates = new MutableLiveData<>();
        }
        return bulbStates;
    }

    public void setBulbStates(boolean[] newBulbStates) {
        bulbStates.setValue(newBulbStates);
    }

    //窗户
    public LiveData<boolean[]> getWindowStates() {
        if (windowStates == null) {
            windowStates = new MutableLiveData<>();
        }
        return windowStates;
    }

    public void setWindowStates(boolean[] newWindowStates) {
        windowStates.setValue(newWindowStates);
    }

    //阳台
    public LiveData<boolean[]> getBalconyStates() {
        if (balconyStates == null) {
            balconyStates = new MutableLiveData<>();
        }
        return balconyStates;
    }

    public void setBalconyStates(boolean[] newBalconyStates) {
        balconyStates.setValue(newBalconyStates);
    }

    //门
    public LiveData<boolean[]> getDoorStates() {
        if (doorStates == null) {
            doorStates = new MutableLiveData<>();
        }
        return doorStates;
    }

    public void setDoorStates(boolean[] newDoorStates) {
        doorStates.setValue(newDoorStates);
    }

    //离家模式
    public LiveData<Boolean> getLeaveHomeState() {
        if (leaveHomeState == null) {
            leaveHomeState = new MutableLiveData<>();
        }
        return leaveHomeState;
    }

    public void setLeaveHomeState(Boolean newLeaveHomeState) {
        leaveHomeState.setValue(newLeaveHomeState);
    }

    //自动调节
    public LiveData<AutoAdaptModel> getAutoAdaptModel() {
        if (autoAdaptModel == null) {
            autoAdaptModel = new MutableLiveData<>();
        }
        return autoAdaptModel;
    }

    public void setAutoAdaptModel(AutoAdaptModel newAutoAdaptModel) {
        autoAdaptModel.setValue(newAutoAdaptModel);
    }

    //路障
    public LiveData<Boolean> getRoadblockState() {
        if (roadblockState == null) {
            roadblockState = new MutableLiveData<>();
        }
        return roadblockState;
    }

    public void setRoadblockState(Boolean newRoadblockState) {
        roadblockState.setValue(newRoadblockState);
    }

    //街灯
    public LiveData<boolean[]> getStreetLampStates() {
        if (streetLampStates == null) {
            streetLampStates = new MutableLiveData<>();
        }
        return streetLampStates;
    }

    public void setStreetLampStates(boolean[] newStreetLampStates) {
        streetLampStates.setValue(newStreetLampStates);
    }
}
